package datastructure.book.dp._1_pathway.all;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class _6_Solution {

    public int minFallingPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        if (m == 1) {
            return grid[0][0];
        }
        int[] result = grid[0];
        int[][] ints = getMinOneTwo(result);
        int[][] cntArr = new int[m][n];
        System.arraycopy(result, 0, cntArr[0], 0, result.length);
        for (int i = 1; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                int num = grid[i][j];
                if (ints[0][2] == 1 && ints[0][1] == j) {
                    cntArr[i][j] = ints[1][0] + num;
                } else {
                    cntArr[i][j] = ints[0][0] + num;
                }
            }
            ints = getMinOneTwo(cntArr[i]);
        }
        int resultCnt = cntArr[m-1][0];
        for (int i = 1; i < cntArr[m - 1].length; i++) {
            resultCnt = Math.min(cntArr[m-1][i],resultCnt);
        }
        return resultCnt;
    }
    private int[][] getMinOneTwo(int[] result){
        int[][] ints = new int[2][2];
        if (result[0] < result[1]) {
            ints[0] = new int[]{result[0],0,1};
            ints[1] = new int[]{result[1],1,1};
        } else {
            ints[0] = new int[]{result[1],1,1};
            ints[1] = new int[]{result[0],0,1};
        }
        for (int j = 2; j < result.length; j++) {
            if (result[j] < ints[0][0]) {
                ints[1] = new int[]{ints[0][0],ints[0][1],ints[0][2]};
                ints[0] = new int[]{result[j],j,1};
            }else if (result[j] == ints[0][0]){
                ints[0][2]++;
            } else if (result[j] < ints[1][0]) {
                ints[1] = new int[]{result[j],j,1};
            }else if (result[j] == ints[1][0]){
                ints[1][2]++;
            }
        }
        return ints;
    }

    @Test
    public void test(){
        int[][] num = new int[][]{
                {50,-18,-38,39,-20,-37,-61,72,22,79},
                {82,26,30,-96,-1,28,87,94,34,-89},
                {55,-50,20,76,-50,59,-58,85,83,-83},
                {39,65,-68,89,-62,-53,74,2,-70,-90},
                {1,57,-70,83,-91,-32,-13,49,-11,58},
                {-55,83,60,-12,-90,-37,-36,-27,-19,-6},
                {76,-53,78,90,70,62,-81,-94,-32,-57},
                {-32,-85,81,25,80,90,-24,10,27,-55},
                {39,54,39,34,-45,17,-2,-61,-81,85},
                {-77,65,76,92,21,68,78,-13,39,22}
        };
        System.out.println(minFallingPathSum(num));
    }
}
